package practice.sort.compare;

import practice.sort.Sort;

/**
 * @Description:
 * @Author Ammar
 * @Create 2023/8/10 13:01
 */
public class CountingSort extends Sort {
    @Override
    public void sort() {
        int min = nums[0];
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > max) max = nums[i];
            if (nums[i] < min) min = nums[i];
        }

        int[] counts = new int[max - min + 1];
        for (int i = 0; i < nums.length; i++) {
            counts[nums[i] - min]++;
        }

        for (int i = 1; i < counts.length; i++) {
            counts[i] += counts[i - 1];
        }

        int[] newNums = new int[nums.length];
        for (int i = nums.length - 1; i >= 0; i--) {
            newNums[--counts[nums[i] - min]] = nums[i];
        }

        for (int i = 0; i < nums.length; i++) {
            nums[i] = newNums[i];
        }
    }
}
